package com.example.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;

import com.example.entity.Authors;
import com.example.handler.CustomResultHandler;
import com.example.mapper.AuthorsMapper;
import com.example.processor.DownloadProcessor;
import com.example.service.AuthorsService;

import lombok.RequiredArgsConstructor;

/**
 * @author : guorf
 * @version : v1.0
 * @description : TODO
 * @createTime : 2023/5/5 17:39
 */
@Service
@RequiredArgsConstructor
public class AuthorsServiceImpl implements AuthorsService {

    private final SqlSessionTemplate sqlSessionTemplate;
    private final AuthorsMapper authorsMapper;

    /**
     * stream读数据写文件方式
     * @param httpServletResponse
     * @throws IOException
     */
    @Override
    public void streamDownload(HttpServletResponse httpServletResponse)
            throws IOException {

        CustomResultHandler customResultHandler = new CustomResultHandler(new DownloadProcessor(httpServletResponse));
        sqlSessionTemplate.select(
                "com.example.mapper.AuthorsMapper.streamByExample", new HashMap<>(), customResultHandler);
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }

    /**
     * 传统下载方式
     * @param httpServletResponse
     * @throws IOException
     */
    @Override
    public void traditionDownload(HttpServletResponse httpServletResponse)
            throws IOException {
        List<Authors> authors = authorsMapper.selectByExample(new Authors());
        DownloadProcessor downloadProcessor = new DownloadProcessor (httpServletResponse);
        authors.forEach (downloadProcessor::processData);
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
